// 监听主线程消息
self.addEventListener('message', (e) => {
    if (e.data.action === 'start') {
        const { expireTime, orderSn } = e.data
        let remaining = expireTime - Date.now()

        const tick = () => {
            remaining -= 1000

            // 发送剩余时间
            self.postMessage({
                type: 'tick',
                remaining: remaining
            })

            // 触发过期
            if (remaining <= 0) {
                self.postMessage({ type: 'expired' })
                clearInterval(interval)
                localStorage.removeItem(`orderExpire_${orderSn}`)
            }
        }

        // 立即执行第一次更新
        tick()

        // 启动定时器
        const interval = setInterval(tick, 1000)
    }
})
// // 📁 countdown.worker.js
// self.onmessage = function(e) {
//     const { action, expireTime, orderSn } = e.data;
//     if (action === 'start') {
//         const timer = setInterval(() => {
//             const remaining = expireTime - Date.now();
//             console.log('[Worker] Remaining:', remaining); // 添加日志
//             if (remaining <= 0) {
//                 clearInterval(timer);
//                 self.postMessage({ type: 'expired', orderSn });
//                 console.log('[Worker] 发送过期事件'); // 确认发送
//             } else {
//                 self.postMessage({ type: 'tick', remaining });
//             }
//         }, 1000);
//     }
// };

// 📁 countdown.worker.js
self.onmessage = function(e) {
    const { action, expireTime, orderSn } = e.data;
    if (action === 'start') {
        const checkExpiration = () => {
            const remaining = expireTime - Date.now();

            if (remaining <= 0) {
                self.postMessage({
                    type: 'expired',
                    orderSn
                });
                localStorage.removeItem(`orderExpire_${orderSn}`);
            } else {
                self.postMessage({
                    type: 'tick',
                    remaining
                });
                // 继续下一次检查
                setTimeout(checkExpiration, 1000);
            }
        };

        // 立即开始检查
        checkExpiration();
    }
};